const express = require("express");
const cors = require("cors");
const { verifyToken } = require("./utils/jwt");
const productRouter = require("./controller/product"); // 假设您已经创建了商品相关的路由处理文件
const userRouter = require("./controller/users");
const orderRouter = require("./controller/order");
const addressRouter = require("./controller/address");
const commentRouter = require("./controller/comment");
const notice = require("./controller/notice");
const adminUser = require("./controller/adminUser");
const banner = require("./controller/banner");
const uploadRouter = require("./controller/upload"); // 引入文件上传路由
const path = require("path");
const app = express();

// 允许跨域
app.use(cors());

// 静态资源
app.use("/files", express.static(path.join(__dirname, "file")));

// 中间件处理JSON请求体
app.use(express.json());

// Token验证中间件
app.use(async (req, res, next) => {
  if (
    req.path === "/users/login" ||
    req.path === "/users/register" ||
    req.path === "/adminUser/admin-login"||
    req.path === "/upload"  // 去掉upload路由验证，因为element-plus未作兼容，会导致未授权！
  ) {
    next();
    return;
  }
  if (req.headers.authorization) {
    const token = req.headers.authorization.split(" ")[1]; // 假设Token在Bearer后面
    try {
      await verifyToken(token);
      next();
    } catch (error) {
      res.status(401).json({ success: false, message: "登陆失效" });
    }
  } else {
    res.status(401).json({ success: false, message: "未提供Token" });
  }
});

// 配置路由
app.use("/products", productRouter);
app.use("/users", userRouter);
app.use("/orders", orderRouter);
app.use("/address", addressRouter);
app.use("/comments", commentRouter);
app.use("/notice", notice);
app.use("/adminUser", adminUser);
app.use("/banners", banner);
app.use("/upload", uploadRouter); // 文件上传路由

// 监听端口4000
app.listen(4000, () => {
  console.log("Server is running on http://localhost:4000");
});

module.exports = app;
